package com.ddh.ddhsanguogame.interceptor;

import com.ddh.ddhsanguogame.utils.JwtUtil;
import com.ddh.ddhsanguogame.utils.UserContextHolder;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletRequest.getServletRequest();

            String token = httpRequest.getHeader("Authorization");
            if (token != null && !token.isEmpty()) {
                String userId = JwtUtil.getUserIdFromToken(token);
                attributes.put("userId", Long.valueOf(userId)); // 存储在会话属性中
                return true;
            }
        }
        return false;
    }


    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 握手完成后的处理
        UserContextHolder.removeUserId();
    }
}
